package com.github.elliot.gatewaycenter.filter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.elliot.gatewaycenter.filter.order.OrderEnum;
import com.github.elliot.gatewaycenter.util.AESEncryptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class ResponseFilter implements GlobalFilter, Ordered {

    @Value("${aes.secretKey:4gl3fb6hS47jzfpXDzuiWkeLVw724JDMv/9My9JQ618=}")
    private String aesSecretKey;

    @Value("${permit.url-list}")
    private List<String> permitUrlList;

    @Value("${response.is-open-encrypt:false}")
    private Boolean isResponseEncrypt;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if(!BooleanUtil.isTrue(isResponseEncrypt) || isInWhiteList(request)){
            return chain.filter(exchange);
        }
        return chain.filter(exchange.mutate()
                .response(serverHttpResponseDecorator(exchange)).build());
    }

    private ServerHttpResponseDecorator serverHttpResponseDecorator(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();

        return new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                // 响应加密
                String contentTypeHeader = response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
                HttpStatusCode statusCode = response.getStatusCode();
                if(Objects.nonNull(statusCode) && statusCode.value() == 200 &&
                        StringUtils.startsWithIgnoreCase(contentTypeHeader, MediaType.TEXT_PLAIN_VALUE)){
                    log.info("执行响应加密");
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                        return super.writeWith(fluxBody.buffer().handle((dataBuffers, sink) -> {
                            DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory()
                                    .join(dataBuffers);
                            byte[] content = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(content);
                            DataBufferUtils.release(dataBuffer);
                            String responseBody = new String(content, StandardCharsets.UTF_8);
                            byte[] bytes = responseBody.getBytes();
                            if(BooleanUtil.isTrue(isResponseEncrypt) && !isInWhiteList(request)){
                                try {
                                    JSONObject json = new JSONObject();
                                    SecretKey secretKey = AESEncryptionUtil.loadKey(aesSecretKey);
                                    String encrypt = AESEncryptionUtil.encrypt(responseBody, secretKey);
                                    json.put("payload", encrypt);
                                    bytes = json.toJSONString().getBytes();
                                } catch (Exception e) {
                                    sink.error(new RuntimeException(e));
                                    return;
                                }
                            }
                            sink.next(bufferFactory.wrap(bytes));
                        }));
                    }
                }
                return super.writeWith(body);
            }
        };
    }

    /**
     * 校验是否在报名单
     * @param request ServerHttpRequest
     * @return boolean
     */
    private boolean isInWhiteList(ServerHttpRequest request){
        if(CollectionUtil.isEmpty(permitUrlList)){
            return false;
        }
        String path = request.getPath().value();
        return permitUrlList.stream().anyMatch(whitePath ->
                path.equals(whitePath) ||
                        path.startsWith(whitePath.replace("/**", ""))
        );
    }

    @Override
    public int getOrder() {
        return OrderEnum.RESPONSE_FILTER.getOrder();
    }
}
